package com.shop.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.alipay.domain.AliPay;
import com.shop.alipay.feign.PayFeign;
import com.shop.config.RabbitMqConfig;
import com.shop.domain.Order;
import com.shop.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class PayListener {
    @Autowired
    private PayFeign payFeign;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RabbitListener(queues = RabbitMqConfig.PAY_DEAD_QUEUE)
    public void pay(String order1){
        Order order = JSONObject.parseObject(order1, Order.class);
        Order orderSelect = new Order();
        orderSelect.setId(order.getId());
        Order order2 = orderService.selectList(orderSelect).get(0);
        if (order2.getStatus()!=0) {
            return;
        }
        // 未付款
        AliPay aliPay = new AliPay();
        aliPay.setTime(order2.getCreateTime().getTime());
        Map map = payFeign.queryPayment(aliPay);
        if(map.get("msg").equals("success")){
            // 支付成功
            order2.setTradeNo(map.get("trade_no").toString());
            order2.setStatus(1);
        }else {
            // 未支付 关闭订单 发消息回滚库存
            rabbitTemplate.convertAndSend("",RabbitMqConfig.ADD_QUEUE, JSON.toJSONString(order2));
            order2.setStatus(7);
        }
        orderService.update(order2);
    }
}
